<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课堂点名系统</title>
    <style>
        :root {
            --primary-color: #4a6fa5;
            --secondary-color: #6b8cae;
            --accent-color: #ff7e5f;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
            --danger-color: #F56C6C;
            --bg-color: #fcf8ec;
        }

        #MP3 {
            display: none;
        }

        #addName {
            display: none;
        }

        #clearHistory {
            float: right;
        }

        html {
            height: 100%;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            min-height: 100%;
            color: var(--dark-color);
            background-color: var(--bg-color);
            margin: 0;
            padding: 20px;
            position: relative;
        }
        body::before {
            content: '';
            position: fixed;
            bottom: 0;
            left: 0;
            width: 256px;
            height: 553px;
            background: url('./imgs/left1.jpeg') no-repeat center/100% 100%;
            pointer-events: none;
        }

        body::after {
            content: '';
            position: fixed;
            bottom: 0;
            right: 0;
            width: 200px;
            height: 220px;
            background: url('./imgs/lu2.png') no-repeat center/100% 100%;
            transform: rotateY(180deg);
            z-index: 9999;
            pointer-events: none;
        }


        .container {
            max-width: 900px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            padding: 30px;
            position: relative;
            z-index: 9999;
        }

        .container::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 148px;
            height: 134px;
            background: url("./imgs/aligate2.png") no-repeat center/100%;
        } 

        .container::after {
            content: "";
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 134px;
            background: url("./imgs/aligate1.png") no-repeat center/100%;
        } 

        h1 {
            color: var(--primary-color);
            text-align: center;
            margin-bottom: 30px;
            font-weight: 600;
        }

        .section {
            margin-bottom: 30px;
            padding: 20px;
            background-color: var(--light-color);
            border-radius: 8px;
        }
      
        .section.hide {
            display: none;
        }

        .section-box {
            display: none;
        }

        .section-box.active {
            display: block;
        }

        h2 {
            color: var(--secondary-color);
            margin-top: 0;
            font-size: 1.4rem;
            border-bottom: 2px solid var(--secondary-color);
            padding-bottom: 10px;
        }

        textarea {
            width: 100%;
            min-height: 168px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            resize: vertical;
            font-family: inherit;
        }

        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            flex-wrap: wrap;
        }

        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s;
            flex-grow: 1;
        }

        button:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
        }

        button:active {
            transform: translateY(0);
        }

        button.accent {
            background-color: var(--accent-color);
        }

        button.danger {
            background-color: var(--danger-color);
        }


        button.accent:hover {
            background-color: #ff6a45;
        }

        .bird {
            position: relative;
        }
        .bird::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 168px;
            height: 118px;
            background: url('./imgs/bird1.png') no-repeat center/100% 100%;
        }

        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        #BACK {
            margin-bottom: 20px;
            float: right;
        }

        .student-list,
        .history-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }

        .student-item,
        .history-item {
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
        }

        .history-item {
            cursor: pointer;
        }

        .history-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.15);
            background-color: var(--accent-color);
            color: white;
            font-weight: bold;
        }

        .student-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.15);
        }

        .student-item.selected {
            background-color: var(--accent-color);
            color: white;
            font-weight: bold;
        }

        .result-area {
            text-align: center;
            margin: 30px 0;
        }

        .selected-student {
            font-size: 2.5rem;
            color: var(--primary-color);
            font-weight: bold;
            margin: 20px 0;
            min-height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .selected-list {
            margin-top: 20px;
            padding: 15px;
            background-color: #f0f4f8;
            border-radius: 8px;
        }

        .selected-list h3 {
            margin-top: 0;
            color: var(--secondary-color);
        }

        .selected-list ul {
            list-style-type: none;
            padding: 0;
            columns: 2;
        }

        .selected-list li {
            padding: 5px 0;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .student-list {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            }

            .selected-list ul {
                columns: 1;
            }
        }
    </style>
</head>

<body>
    <audio id="MP3" src="./music/bg_music.mp3"></audio>
    <div class="container">
        <h1 id="systemTitle">课堂点名系统</h1>

        <div id="CREATE" class="section-box active">
            <div class="section one">
                <h2>学生名单录入</h2>
                <p>请输入学生姓名，每行一个名字：</p>
                <textarea id="nameInput" placeholder="例如：
张三
李四
王五"></textarea>
                <div class="button-group">
                    <button id="loadNames">录入完成</button>
                    <button id="clearNames">清空名单</button>
                    <button id="addName">添加单个学生</button>
                </div>
            </div>

            <div class="section hide">
                <h2>历史名单
                    <button id="clearHistory" class="danger">清空历史名单</button>
                </h2>
                <div class="history-list" id="historyList">
                </div>
            </div>
        </div>


        <div id="MAIN" class="section-box ">
            <div class="section">
                <h2>学生名单</h2>
                <p>当前学生总数: <span id="studentCount">0</span></p>
                <div class="student-list" id="studentList"></div>
            </div>

            <div class="bird clearfix">
                <button id="BACK">重新录入学生</button>
            </div>

            <div class="section">
                <h2>点名</h2>
                <div class="result-area">
                    <div class="selected-student" id="selectedStudent">开始点名咯</div>
                    <div class="button-group">
                        <button id="randomSelect" class="accent">随机点名</button>
                        <button id="randomExtract" class="danger">随机抽取</button>
                        <button id="resetSelection">重置已点名单</button>
                    </div>
                </div>

                <div class="selected-list">
                    <h3>已点学生 (<span id="selectedCount">0</span>)</h3>
                    <ul id="selectedList"></ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let isLoading = false; // 是否正在点名
            let randomIndex = 0; // 要点名的学生索引
            let randomIndexList = []; // 随机抽取的学生索引列表
            let selected = null; // 点到的学生
            let selectedList = []; // 批量抽取到的学生

            // 获取DOM元素

            const nameInput = document.getElementById('nameInput');
            // 录入按钮
            const loadNamesBtn = document.getElementById('loadNames');
            // 清空录入名单按钮
            const clearNamesBtn = document.getElementById('clearNames');
            const addNameBtn = document.getElementById('addName');
            // 学生列表容器
            const studentList = document.getElementById('studentList');
            // 学生数量
            const studentCount = document.getElementById('studentCount');
            // 随机抽取按钮
            const randomSelectBtn = document.getElementById('randomSelect');
            // 批量随机抽取按钮
            const randomExtractBtn = document.getElementById('randomExtract');
            // 重置按钮
            const resetSelectionBtn = document.getElementById('resetSelection');

            // 选中的学生信息
            const selectedStudent = document.getElementById('selectedStudent');
            // 选中的学生列表
            const selectedListDom = document.getElementById('selectedList');
            // 已点过的学生数量
            const selectedCount = document.getElementById('selectedCount');

            // 录入页面
            const create = document.getElementById("CREATE");
            // 点名页面
            const main = document.getElementById("MAIN");

            // 返回
            const back = document.getElementById("BACK");

            // 配乐
            const mp3 = document.getElementById("MP3")

            // 历史记录容器
            const historyListDom = document.getElementById('historyList');

            // 清空历史记录
            const clearHistory = document.getElementById('clearHistory');

            // 系统名称
            const systemTitle = document.getElementById('systemTitle');

            // 存储学生名单和已点学生
            let students = [];
            let selectedStudents = [];


            function goClass(key) {
                // 获取历史名单列表
                const historyObj = JSON.parse(localStorage.getItem('historyObj')) || {};

                // 获取历史选择班级key
                const historyKey = key || localStorage.getItem('historyKey') || '';

                if (historyKey && historyObj[historyKey]) {
                    localStorage.setItem('historyKey', historyKey);

                    systemTitle.innerHTML = `课堂点名系统（${historyKey}）`
                    students = historyObj[historyKey];
                    create.classList.remove('active');
                    main.classList.add('active');
                    updateStudentList();
                }
            }

            randomExtractBtn.addEventListener('click', function() {
                if (students.length === 0) {
                    alert('请先录入学生名单！');
                    return;
                }
                
                // 找出未点名的学生
                const availableStudents = students.filter(student => !selectedStudents.includes(student));
                if (availableStudents.length === 0) {
                    alert('所有学生都已被点到！');
                    return;
                }

                if (isLoading) {
                    return
                }

                const num = prompt('请输入批量抽取个数:');
                const reg = /^[1-9]\d*$/

                if (num && num.trim() && reg.test(num.trim())) {

                    const resultNum = Number(num.trim())
                    if (resultNum > availableStudents.length) {
                        alert('批量抽取个数不能大于未抽点的学生总数！');
                        return;
                    }
                    isLoading = true
                    mp3.play()
                    // 随机选择
                    const timer = setInterval(() => {
                        // 随机选择 解决最近一次和上一次会重复的问题
                        randomIndexList = getRandomNumberList(resultNum, availableStudents.length)

                        selectedList = []
                        for (let i = 0; i < randomIndexList.length; i++) {
                            const index = randomIndexList[i]
                            const selected = availableStudents[index].trim();
                            selectedList.push(`${selected}`)
                        }

                        // 显示结果
                        selectedStudent.textContent = selectedList.join("、");

                        // 高亮显示
                        highlightSelectedStudentList(selectedList);
                    }, 200)

                    setTimeout(() => {
                        window.clearInterval(timer)
                        for (let i = 0; i < selectedList.length; i++) {
                            const item = selectedList[i];
                            // 添加到已点名单
                            if (!selectedStudents.includes(item)) {
                                selectedStudents.push(item);
                            }
                        }

                        updateSelectedList();
                        isLoading = false
                    }, 4000)
                } else {
                    alert('请输入正确的批量抽取个数！')
                    return
                }

            });

            function highlightSelectedStudentList(selectedList) {
        
                document.querySelectorAll('.student-item').forEach(item => {
                    if (selectedList.includes(item.textContent)) {
                        item.classList.add('selected');
                    } else {
                        item.classList.remove('selected');
                    }
                });
            }

            // 3. 使用事件委托绑定点击班级事件
            historyListDom.addEventListener('click', function(event) {
                if (event.target.classList.contains('history-item')) {
                    const buttonId = event.target.dataset.id;
                    goClass(buttonId)
                }
            });

            // 清空班级列表
            clearHistory.addEventListener('click', function() {
                const isClearHistory = confirm("是否确定清空历史记录？")
                if (isClearHistory) {
                    localStorage.removeItem('historyObj');
                    localStorage.removeItem('historyKey');
                    updateHistoryList()
                }
            });


            // 返回按钮
            back.addEventListener("click", function() {
                create.classList.add('active');
                main.classList.remove('active');
                systemTitle.innerHTML = `课堂点名系统`
                students = [];
                selectedStudents = [];
                updateStudentList(true); // 不清理nameInput的内容
                updateSelectedList();
                selectedStudent.textContent = '请开始点名';
            })

            // 载入名单
            loadNamesBtn.addEventListener('click', function() {
                const namesText = nameInput.value.trim();
                if (namesText) {
                    const resultStudents = namesText.split('\n')
                        .map(name => name.trim())
                        .filter(name => name.length > 0);

                    students = [...new Set(resultStudents)]
                    if (students.length !== resultStudents.length) {
                        alert('有重复学生，请检查输入！')
                        return
                    }
                    const isSaveClass = confirm("是否将班级名单保存到浏览器？")
                    if (isSaveClass) {
                        // 获取历史名单列表
                        const classObj = JSON.parse(localStorage.getItem('historyObj')) || {};
                        const classList = Object.keys(classObj);
                        const name = prompt('请输入班级名称:');
                        if (name && name.trim()) {
                            if (classList.includes(name.trim())) {
                                alert('该班级已存在，请勿重复添加！');
                                return;
                            }
                            classObj[name.trim()] = students;
                            localStorage.setItem('historyObj', JSON.stringify(classObj));
                            localStorage.setItem('historyKey', name.trim());

                            systemTitle.innerHTML = `课堂点名系统（${name.trim()}）`

                            create.classList.remove('active');
                            main.classList.add('active');
                            updateStudentList();

                            updateHistoryList()
                        }
                    } else {
                        create.classList.remove('active');
                        main.classList.add('active');
                        updateStudentList();
                    }
                } else {
                    alert('请输入录入学生名单！')
                }
            });

            // 清空名单
            clearNamesBtn.addEventListener('click', function() {
                students = [];
                selectedStudents = [];
                updateStudentList();
                updateSelectedList();
                nameInput.value = '';
                selectedStudent.textContent = '请开始点名';
            });

            // 添加单个学生
            addNameBtn.addEventListener('click', function() {
                const name = prompt('请输入学生姓名:');
                if (name && name.trim()) {
                    if (students.includes(name.trim())) {
                        alert('该学生已存在，请勿重复添加！');
                        return;
                    }
                    students.push(name.trim());
                    updateStudentList();
                }
            });

            // 随机点名
            randomSelectBtn.addEventListener('click', function() {
                if (students.length === 0) {
                    alert('请先录入学生名单！');
                    return;
                }

                // 找出未点名的学生
                const availableStudents = students.filter(student => !selectedStudents.includes(student));

                if (availableStudents.length === 0) {
                    alert('所有学生都已被点到！');
                    return;
                }

                if (isLoading) {
                    return
                }
                isLoading = true

                mp3.play()

                // 随机选择
                const timer = setInterval(() => {
                    // 随机选择 解决最近一次和上一次会重复的问题
                    randomIndex = getRandomNumber(randomIndex, availableStudents.length)

                    selected = availableStudents[randomIndex];

                    // 显示结果
                    selectedStudent.textContent = selected;

                    // 高亮显示
                    highlightSelectedStudent(selected);
                }, 200)

                setTimeout(() => {
                    window.clearInterval(timer)
                    // 添加到已点名单
                    if (!selectedStudents.includes(selected)) {
                        selectedStudents.push(selected);
                        updateSelectedList();
                    }
                    isLoading = false
                }, 4000)

            });

            // 重置已点名单
            resetSelectionBtn.addEventListener('click', function() {
                selectedStudents = [];
                updateSelectedList();
                selectedStudent.textContent = '请开始点名';

                // 移除所有高亮
                document.querySelectorAll('.student-item').forEach(item => {
                    item.classList.remove('selected');
                });
            });

            // 获取随机数字
            function getRandomNumber(preRandomIndex, max) {
                // 随机选择
                let newRandomIndex = Math.floor(Math.random() * max);
                // 解决动画不会变问题
                if (newRandomIndex === preRandomIndex && max > 1) {
                    return getRandomNumber(preRandomIndex, max)
                }
                return newRandomIndex
            }

            // 获取随机数字 只用一次 num 获取随机数数量 max 最大值
            function getRandomNumberList(num, max) {
                let randomIndexList = []
                while (randomIndexList.length < num) {
                    // 随机选择
                    let newRandomIndex = Math.floor(Math.random() * max);
                    if (!randomIndexList.includes(newRandomIndex)) {
                        randomIndexList.push(newRandomIndex)
                    }
                }
                
                return randomIndexList
            }

            function updateHistoryList() {
                historyListDom.innerHTML = '';

                // 获取历史名单列表
                const historyObj = JSON.parse(localStorage.getItem('historyObj')) || {};
                // 获取历史选择班级key
                const historyKey = localStorage.getItem('historyKey') || '';
                if (JSON.stringify(historyObj) !== "{}") {
                    const list = Object.keys(historyObj);
                    list.forEach(name => {
                        const historyItem = document.createElement('div');
                        historyItem.classList.add('history-item');
                        historyItem.dataset.id = name; // 添加自定义数据属性
                        historyItem.textContent = name;
                        historyListDom.appendChild(historyItem);
                    });
                    historyListDom.parentElement.classList.remove('hide')
                } else {
                    historyListDom.parentElement.classList.add('hide')
                }

            }

            // 更新学生列表显示
            function updateStudentList(noClearNameInput) {
                let inputHtml = '';
                studentList.innerHTML = '';
                students.forEach(student => {
                    const studentItem = document.createElement('div');
                    studentItem.className = 'student-item';
                    studentItem.textContent = student;
                    studentList.appendChild(studentItem);
                    inputHtml += `${student}\n`;
                });
                if (!noClearNameInput) {
                    nameInput.value = inputHtml.trim();
                }
                studentCount.textContent = students.length;
            }

            // 更新已点名单显示
            function updateSelectedList() {
                selectedListDom.innerHTML = '';
                selectedStudents.forEach(student => {
                    const li = document.createElement('li');
                    li.textContent = student;
                    selectedListDom.appendChild(li);
                });
                selectedCount.textContent = selectedStudents.length;
            }

            // 高亮显示被选中的学生
            function highlightSelectedStudent(name) {
                // 先移除所有高亮
                document.querySelectorAll('.student-item').forEach(item => {
                    item.classList.remove('selected');
                });

                // 添加新的高亮
                document.querySelectorAll('.student-item').forEach(item => {
                    if (item.textContent === name) {
                        item.classList.add('selected');
                    }
                });
            }

            // 初始化
            updateStudentList();
            updateSelectedList();

            // 更新历史班级列表
            updateHistoryList()

            // 有班级前往班级
            goClass()
        });
    </script>
</body>

</html>